package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.service.IApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements IApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        // 判断，关键字为空不需要查询
        if (StringUtils.isEmpty(dto.getSearchWords().trim())) {
            return null;
        }
        // regex正则模糊查询
        Query query = new Query(Criteria.where("associateWords").regex(dto.getSearchWords()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime")); //时间排序
        query.limit(5); //只要5个
        List<ApAssociateWords> list = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(list);
    }
}
